<?php
namespace Core\Forms\Element;

use Phalcon\Tag;
use Phalcon\Di;
use Core\Forms\Element;

class Date extends Element
{
    public function getValue()
    {
        $value = parent::getValue();
        $value = strtotime('Y-m-d H:i:s',(int)$value);
        $value = intval($value);
        return $value;
    }

    public function getDefault()
    {
        $default = parent::getDefault();
        if(!is_int($default)){
            $default = time();
        }
        return date('Y-m-d H:i:s', $default);
    }

    public function render($attributes = null)
    {
        $di = Di::getDefault();

        if (!isset($this->_options['format'])) {
            $this->_options['format'] = 'YYYY-MM-DD hh:mm:ss';
        }
        $value = $this->_value;
        $date = $value ? $value : date('Y-m-d H:i:s', time());
        $scription =
<<<scription
    $('#{$this->_name}').datetimepicker({
        format: '{$this->_options['format']}',
        defaultDate: '{$date}'
    });
scription;

        $di->getShared('assets')
            ->addJs('bootstrap-datetimepicker', '//cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js', 'footer')
            ->addJs('bootstrap-datetimepicker-zh', '//cdn.bootcss.com/bootstrap-datetimepicker/2.1.30/js/locales/bootstrap-datetimepicker.zh-CN.js', 'footer')
            ->addCss('bootstrap-datetimepicker', '//cdn.bootcss.com/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css', 'footer')
            ->addInlineJs('bootstrap-datetimepicker-init-' . $this->_name, $scription, 'footer');

        return Tag::dateField($this->prepareAttributes($attributes));
    }
}
